﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWebSocket>
#include <QWebSocketServer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

/*
 * 创建QT WebSocket Server端
 * Server侦听ui界面指定的HostAddress及Port
 * 将QT WebSocketServer newConnection信号与 ui界面onNewConnection槽函数绑定
*/
void MainWindow::On_Open_Socket_Server_clicked()
{
    myServer = new QWebSocketServer("Server", QWebSocketServer::NonSecureMode, this);

    if(!ui->line_HostAddress->text().isEmpty() && !ui->Line_Port->text().isEmpty())
    {
        if(myServer->listen(QHostAddress(ui->line_HostAddress->text()), ui->Line_Port->text().toUInt()))
        {
            qDebug() << "server listen to " << QHostAddress(ui->line_HostAddress->text()).toString() << "port:" << ui->Line_Port->text().toUInt();
            connect(myServer, &QWebSocketServer::newConnection, this, &MainWindow::OnNewConnection);
        }
    }
}

/*
 * 创建QT WebSocket Client端
 * Client 连接到ui界面指定的URL
 * 将QT WebSocket textMessageReceived信号与 ui界面Receive_Server_Message槽函数绑定
*/
void MainWindow::On_Open_Socket_Client_clicked()
{
    myClient = new QWebSocket;

    if(!ui->Line_URL->text().isEmpty())
    {
        myClient->open(QUrl(ui->Line_URL->text()));
        if(!myClient->requestUrl().isEmpty())
            qDebug() << "client connect to" << QString(myClient->requestUrl().toString());

        connect(myClient, &QWebSocket::textMessageReceived, this, &MainWindow::Receive_Server_Message);
    }
}

/*
 * 获取server下 第一个socket
 * qt的websocket server本身只有listen功能 发送和接收消息需要依靠server建立一个属于自己的websocket来接收和发送来自client的消息
*/

void MainWindow::On_Server_send_clicked()
{
    for (QWebSocket *server_send_socket : myClientList) {
        server_send_socket->sendTextMessage(ui->Server_message->text());
    }
}

/*
 * client发送消息
*/
void MainWindow::On_Client_send_clicked()
{
    myClient->sendTextMessage(ui->Client_message->text());
}

/*
 * server检测到了新连接
 * server建立自己的websocket用于接收来自新连接的消息
 * 属于server的websocket将其 textMessageReceived信号与ui界面 Receive_Client_Message槽函数绑定
*/
void MainWindow::OnNewConnection()
{
    qDebug() << "new connection build";
    QWebSocket *server_socket = myServer->nextPendingConnection();
    if(!server_socket)
         return;

    myClientList.push_back(server_socket);

    connect(server_socket, &QWebSocket::textMessageReceived, this, &MainWindow::Receive_Client_Message);
}

/*
 * 打印来自client端消息 以实时时间为标识
*/
void MainWindow::Receive_Client_Message(const QString &message)
{
    QTime current_time = QTime::currentTime();
    ui->text_Server->append(QString(current_time.toString()) + "  " + QString(message));
}

/*
 * 打印来自server端消息 以实时时间为标识
*/
void MainWindow::Receive_Server_Message(const QString &message)
{
    QTime current_time = QTime::currentTime();
    ui->text_Client->append(QString(current_time.toString()) + "  " +QString(message));
}
